<script lang="ts" setup>
import type { VxeGridListeners, VxeTableGridOptions } from '#/adapter/vxe-table'

import { markRaw, onMounted, onUnmounted, ref, watch } from 'vue'

import { Page, useVbenModal } from '@vben/common-ui'

import {
  Button,
  Dropdown,
  Input,
  Menu,
  MenuItem,
  message,
  Popconfirm,
  Space,
  Switch
} from 'ant-design-vue'

import fileManage from '#/adapter/component/FileManage/index.vue'
import { useVbenVxeGrid } from '#/adapter/vxe-table'
import { againstSupply, approvalSupply, delSupply, editSupply, getContractList, SupplyExcel, supplylList } from '#/api/supply'
import TwoFields from '#/views/backend/modules/two-fields.vue'

import exportList from './modules/exportList.vue'
import popupForm from './modules/popupForm.vue'

const searchValue = ref()
const formOptions: any = {
  collapsed: true,
  submitOnChange: false,
  // 按下回车时是否提交表单
  submitOnEnter: true,
  wrapperClass: 'grid-cols-5',
  layout: 'horizontal',
  schema: [
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'Supplyid',
      label: '编码',
      operator: 'LIKE',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'Xingzhi',
      label: '性质',
      operator: 'LIKE',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'Leibie',
      label: '类别',
      operator: 'LIKE',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'Supplyman1',
      label: '联系人1',
      operator: 'LIKE',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'Supplytel1',
      label: '手机号1',
      operator: 'LIKE',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'Supplyadd',
      label: '地址',
      operator: 'LIKE',
    },
    {
      component: markRaw(TwoFields),
      fieldName: 'Taxrate',
      disabledOnChangeListener: false,
      label: '税率',
      operator: 'RANGE',
      valueToString: true,
      componentProps: {
        allowClear: true,
        placeholder: '范围筛选',
      },
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'UserSupplygroup',
      label: '权限分组',
      operator: 'LIKE',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: [
          {
            label: '未上传',
            value: 0,
          },
          {
            label: '已上传',
            value: 1,
          },
        ],
        showSearch: true,
      },
      label: '是否上传附件',
      fieldName: 'isUploadFile',
      operator: 'false',
    },

    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'Operator',
      label: '操作员',
      operator: 'LIKE',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'PostUser',
      label: '审核人',
      operator: 'LIKE',
    },
  ],
  // 是否可展开
  showCollapseButton: true,
  submitButtonOptions: {
    content: '查询',
  },
}
const gridOptions: VxeTableGridOptions = {
  checkboxConfig: {
    highlight: true,
    labelField: 'name',
    trigger: 'row',
  },
  cellConfig: {
    height: 80,
  },
  height: 'auto',
  columns: [
    {
      type: 'checkbox', // 多选列（自带全选框）
      width: 50, // 列宽
      align: 'center', // 居中
      fixed: 'left', // 固定在最左侧
      title: '', // 表头文字
    },
    {
      field: 'Supplyid',
      title: '编码',
      width: 80,
    },
    {
      title: '供应商',
      field: 'SupplyNa',
      width: 250,
      align: 'left',
      headerAlign: 'center',
      slots: { default: 'SupplyNa' },
    },
    { field: 'Xingzhi', title: '性质', width: 80 },
    { field: 'Leibie', title: '类别', width: 80 },
    {
      field: 'Supplyman1',
      title: '联系人1',

    },
    {
      title: '手机号码1',
      field: 'Supplytel1',

    },
    {
      title: '含税',
      field: 'Istaxrate',

      slots: { default: 'Istaxrate' },
    },
    {
      title: '税率',
      field: 'Taxrate',

    },
    {
      title: '权限分组',
      field: 'UserSupplygroup',

    },
    {
      title: '是否上传附件',
      field: 'isUploadFile',

      cellRender: {
        name: 'CellTag',
        options: [
          {
            color: 'success',
            label: '已上传',
            value: 1,
          },
          { color: 'error', label: '未上传', value: 0 },
        ],
      },
    },
    {
      title: '录入时间',
      field: 'InputDate',

    },

    {
      title: '操作员',
      field: 'Operator',

    },
    {
      title: '审核',
      field: 'Posted',

      cellRender: {
        name: 'CellTag',
        options: [
          {
            color: 'success',
            label: '已审核',
            value: 1,
          },
          { color: 'error', label: '未审核', value: 0 },
        ],
      },
    },
    {
      title: '审核时间',
      field: 'PostedDate',
    },
    {
      title: '审核员',
      field: 'PostUser',
    },
    {
      field: 'action',
      title: '操作',
      fixed: 'right',
      slots: { default: 'action' },
    },
  ],
  exportConfig: {},
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        const search: any[] = []
        for (const [key, value] of Object.entries(formValues)) {
          if (value === null || value === '' || value === undefined) continue
          const fieldSchema = formOptions.schema.find((i: any) => i.fieldName === key)
          // 处理特殊字段格式
          let fieldValue = value
          if (key === 'Taxrate') {
            // 将日期范围数组转换为字符串格式："开始时间,结束时间"
            fieldValue = value.join(',')
          }
          search.push({
            field: key,
            val: fieldValue,
            operator: fieldSchema?.operator,
            render: fieldSchema?.render,
          })
        }
        searchValue.value = search
        const res = await supplylList({
          page: page.currentPage,
          limit: page.pageSize,
          quick_search:quick_search.value,
          search,
          Supplytype: 1,
        })
        // 将接口返回的1/0转换为布尔值
        res.list.forEach((row) => {
          row.Istaxrate = row.Istaxrate === 1
        })
        return { items: res.list, total: res.total }
      },
    },
    sort: true,
  },

  id: 'supply_list',
  customConfig: {
    storage: true,
  },
  toolbarConfig: {
    search: true,
    custom: true,
    export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
  rowClassName({ row }) {
    return row.Posted === 0 ? 'text-red-500' : ''
  },
}

// 双击打开编辑
const gridEvents: VxeGridListeners = {
  cellDblclick: ({ row }) => {
    openEdit(row, 'edit')
  },
}
const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents,
})

//  按钮的禁用状态
const isDisabled = ref(true)

const isApprovalDisabled = ref(true)
const isDeleteDisabled = ref(true)

// 检查并更新拷贝按钮状态
function checkCopyButtonStatus() {
  try {
    if (gridApi?.grid?.getCheckboxRecords) {
      const selectedRecords = gridApi.grid.getCheckboxRecords()
      // 检查是否包含已财务标记的记录
      isDisabled.value = !selectedRecords || selectedRecords.length === 0
      const hasApprovalCondition = selectedRecords.some(
        (post) =>
          (post.posted !== undefined && post.post_time !== undefined && post.post_time == null) || // 单据
          post.Posted == 0 ||
          (post.posted !== undefined && post.post_time !== undefined && post.post_time == 0) ||
          (post.posted !== undefined && post.posted == 0) ||
          (post.state !== undefined && post.state == 10),
      )

      isApprovalDisabled.value = !hasApprovalCondition

      // 删除按钮禁用逻辑 - 示例逻辑，需根据实际业务规则调整
      isDeleteDisabled.value = !selectedRecords || selectedRecords.length === 0 || !hasApprovalCondition
    } else {
      isDisabled.value = true
      isApprovalDisabled.value = true
      isDeleteDisabled.value = true
    }
  } catch {
    isDisabled.value = true
    isApprovalDisabled.value = true
  }
}

// 使用watch监听gridApi的变化
watch(
  () => gridApi?.grid,
  (newGrid) => {
    if (newGrid) {
      // 当grid可用时，立即检查一次状态
      checkCopyButtonStatus()
      // 设置一个定时器定期检查选中状态变化
      const interval = setInterval(() => {
        if (gridApi?.grid) {
          checkCopyButtonStatus()
        }
      }, 300) // 每300ms检查一次
      // 组件卸载时清除定时器
      onUnmounted(() => {
        clearInterval(interval)
      })
    }
  },
  { immediate: true },
)
/**
 *  快速查询查询
 */
const quick_search = ref()
function doSearch() {
  gridApi.query()
}
// 删除
function delRow() {
  const data = gridApi.grid.getCheckboxRecords()
  delSupply({ ids: data.map((item) => item.id) }).then((res: any) => {
    if (res.data.code === 0) {
      message.error(res.data.msg)
    } else {
      message.success(res.data.msg)
      gridApi.reload()
    }
  })
}
// 审核
function approvalBut() {
  const data = gridApi.grid.getCheckboxRecords()

  const ids = data.map((record: any) => record.id)
  approvalSupply({ ids, is_confirm_ware: 0 }).then((res: any) => {
    if (res.data.code !== 1) {
      message.error(res.data.msg)
      return
    }
    gridApi.reload()
    message.success('审核成功')
  })
}

function againstShow() {
  const data = gridApi.grid.getCheckboxRecords()
  let is_have_Posted_data = false
  data.forEach((item, index) => {
    if (item.Posted == 0) {
      is_have_Posted_data = true
    }
  })
  if (is_have_Posted_data) {
    message.error('存在未审核的数据，无法反审')
    return false
  } else {
    const data = gridApi.grid.getCheckboxRecords()
    againstSupply({ ids: data.map((item) => item.id) }).then((res: any) => {
      if (res.data.code === 0) {
        message.error(res.data.msg)
      } else {
        message.success(res.data.msg)
        gridApi.reload()
      }
    })
  }
}

function modelClose() {
  gridApi.reload()
}

const [formModal, formModalApi] = useVbenModal({
  connectedComponent: popupForm,
})
// 编辑
function openEdit(res: any, but: any) {
  formModalApi.setData({ rowData: res, view: but }).open()
}

function openContractModalApi() {
  const parmas = {
    Supplytype: 1,
    search: searchValue.value,
  }
  SupplyExcel(parmas).then((res: any) => {
    if (res.data.code === 1) {
      window.open(res.data.data.path)
      message.success(res.data.data.msg)
    } else {
      message.error(res.data.data.msg)
    }
  })
}

// 合同管理
const [fileManageModal, fileManageModalApi] = useVbenModal({
  connectedComponent: fileManage,
})

function openFileModal() {
  const data = gridApi.grid.getCheckboxRecords()
  const ids = data.map((item: any) => item.id)
  fileManageModalApi.setData({ data: ids, type: '3', search: searchValue.value }).open()
}
const [exportModal, exportModalApi] = useVbenModal({
  connectedComponent: exportList,
})

function exportContractModule(data: any) {
  const row = gridApi.grid.getCheckboxRecords()
  exportModalApi.setData({ data: row.map((item: any) => item.id), contract_type: data.key }).open()
}
const contractList = ref({})
onMounted(() => {
  getContractList().then((res: any) => {
    // 确保contractList是一个对象，根据API返回格式提取正确的数据
    contractList.value = res || {}
  })
})

function changeIstaxrate(data: any, row: any) {
  editSupply({ id: row.id, Istaxrate: data ? 1 : 0 }).then((res: any) => {
    if (res.data.code === 0) {
      message.error(res.data.msg)
    } else {
      message.success(res.data.msg)
      gridApi.reload()
    }
  })
}
</script>

<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-actions>
        <div>
          <Space>
            <Button type="primary" @click="openEdit('', 'add')">新建</Button>
            <Popconfirm title="删除选中行" ok-text="确认" cancel-text="取消" @confirm="delRow()">
              <Button type="primary" danger title="删除选中行" :disabled="isDeleteDisabled"> 删除 </Button>
            </Popconfirm>
            <template v-if="!isApprovalDisabled">
              <Popconfirm title="确定审核选中记录" ok-text="确认" cancel-text="取消" @confirm="approvalBut()">
                <Button type="primary" class="my-green-btn" title="审核选中行" :disabled="isApprovalDisabled"> 审核 </Button>
              </Popconfirm>
            </template>
            <template v-else>
              <Button type="primary" title="审核选中行" disabled> 审核 </Button>
            </template>
            <Button type="primary" danger :disabled="isDisabled" @click="againstShow()"> 反审 </Button>

            <Button type="primary" @click="openContractModalApi"> 导出 </Button>
            <Button type="primary" class="my-green-btn" @click="openFileModal()"> 附件管理与导出 </Button>
            <Dropdown>
              <Button type="primary" v-if="!isDisabled">导出框架合同</Button>
              <template #overlay>
                <Menu @click="exportContractModule">
                  <MenuItem v-for="(value, key) in contractList" :key="key">
                    {{ value }}
                  </MenuItem>
                </Menu>
              </template>
            </Dropdown>
          </Space>
        </div>
      </template>

      <template #toolbar-tools>
        <Input v-model:value="quick_search" allow-clear placeholder="通ID、供应商编号、供应商名称模糊搜索" style="width: 300px; margin-right: 8px" @change="doSearch" />
      </template>
      <!-- 操作列插槽 -->
      <template #SupplyNa="{ row }">
        <div>简称: {{ row.SupplyNaStr }}</div>
        <div>全称： {{ row.SupplyName }}</div>
      </template>
      <template #Istaxrate="{ row }">
        <Switch v-model:checked="row.Istaxrate" @change="(val) => changeIstaxrate(val, row)" />
      </template>

      <!-- 操作列插槽 -->
      <template #action="{ row }">
        <Space>
          <Button type="primary" size="small" @click="openEdit(row, 'edit')"> 编辑 </Button>
        </Space>
      </template>
    </Grid>
    <formModal @refresh="modelClose()" />
    <fileManageModal @close="modelClose()" />
    <exportModal @refresh="modelClose()" />
  </Page>
</template>
<style lang="scss" scoped>
.my-green-btn.ant-btn-primary {
  background-color: #67c23a;
  border-color: #67c23a;
}

.my-yello-btn.ant-btn-primary {
  background-color: #e6a23c;
  border-color: #e6a23c;
}
</style>
